package com.wsc.wisdomchina.activitity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.loopj.android.http.RequestParams;
import com.samton.floatWindow.FloatWindowService;
import com.samton.floatWindow.MyWindowManager;
import com.samton.interfaces.IBenHttpCallBack;
import com.samton.mainSDK.MainSDK;
import com.samton.model.Constants;
import com.tencent.android.tpush.XGPushConfig;
import com.umeng.analytics.MobclickAgent;
import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.Tools.AbPermissionUtils;
import com.wsc.wisdomchina.Tools.JsonTools;
import com.wsc.wisdomchina.Tools.Tools;
import com.wsc.wisdomchina.Tools.UpdateManager;
import com.wsc.wisdomchina.activitity.baseactivity.BaseFragmentActivity;
import com.wsc.wisdomchina.adapter.HomeModuleSubAdapter;
import com.wsc.wisdomchina.ai.IBenDemoChatActivity;
import com.wsc.wisdomchina.application.MyApplication;
import com.wsc.wisdomchina.callback.ClickIntoFragment;
import com.wsc.wisdomchina.callback.ContributorView;
import com.wsc.wisdomchina.constant.Constant;
import com.wsc.wisdomchina.fragment.BanKuaiFragment;
import com.wsc.wisdomchina.fragment.ConvenienceFragment;
import com.wsc.wisdomchina.fragment.HomeFragment;
import com.wsc.wisdomchina.fragment.InfoFragment;
import com.wsc.wisdomchina.fragment.MineFragment;
import com.wsc.wisdomchina.fragment.ModuleFragment;
import com.wsc.wisdomchina.javaBean.HomeModuleSubBean;
import com.wsc.wisdomchina.javaBean.RespObj;
import com.wsc.wisdomchina.javaBean.StreetInfoListBean;
import com.wsc.wisdomchina.javaBean.UpdateInfo;
import com.wsc.wisdomchina.presenter.ContributorPresenter;
import com.wsc.wisdomchina.view.MyToast;
import com.wsc.wisdomchina.view.iphoneDialogBuilder;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author jaily.zhang
 * @version V1.3.1
 * @Description 主程序界面
 * @date 2014-7-23 下午3:57:47
 */

public class HomeActivity extends BaseFragmentActivity implements OnClickListener, ClickIntoFragment,ContributorView{
    private Fragment mContent;
    private RadioButton rb_first, rb_info, rb_my,rb_bankuai;
    private HomeFragment homeFragment;
    private MineFragment mineFragment;
    private ConvenienceFragment infoFragment;
    private ModuleFragment banKuaiFragment;
    private Context context;
    private String fragmentFlag;
    private MyApplication myApplication;
    private ContributorPresenter contributorPresenter;
    private final String VERSION_FLAG="VERSION_FLAG";

    private String cidNumber;
    private StreetInfoListBean streetInfoListBean;
    public static MainSDK mainSdk;
    private RelativeLayout layout_show;
    private TextView tv_confirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_layout);
        context=this;
        contributorPresenter=new ContributorPresenter(this,context);
        myApplication=(MyApplication) getApplication();
        // 初始化控件
        initView();
        homeFragment = new HomeFragment();
        fragmentFlag=HomeFragment.class.getSimpleName();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fragment_content, homeFragment, Constant.homeFragmentTag); // 隐藏当前的fragment，add下一个到Activity中
        mContent = homeFragment;
        transaction.commit();

        boolean isUpdate = Tools.getSharedPreferencesboolen(Constant.isUpdate, false,context);
        String locationString = Tools.getSharedPreferencesStrings(Constant.SharePreferenceLocation, "", context);
        if (locationString.length() > 0) {
            streetInfoListBean = JsonTools.jsonStringToObject(locationString, StreetInfoListBean.class);
            cidNumber=streetInfoListBean.getId();
        }
        if (!isUpdate) {
            contributorPresenter.getVersionInfo(cidNumber,VERSION_FLAG);
        }
        init();
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        mainSdk.setFloat(true, IBenDemoChatActivity.class);
    }
    private void init() {
        //小笨sdk  初始化
        mainSdk = MyApplication.getMainSdk();
        // 初始化悬浮窗
        mainSdk.setFloat(true, IBenDemoChatActivity.class);

    }
    /**
     * @Description 初始化控件
     * @author jaily.zhang
     */
    private void initView() {
        rb_first = (RadioButton) findViewById(R.id.rb_first);
        rb_info = (RadioButton) findViewById(R.id.rb_info);
        rb_my = (RadioButton) findViewById(R.id.rb_my);
        rb_bankuai=(RadioButton) findViewById(R.id.rb_bankuai);
        rb_info.setOnClickListener(this);
        rb_first.setOnClickListener(this);
        rb_my.setOnClickListener(this);
        rb_bankuai.setOnClickListener(this);
        layout_show=(RelativeLayout) findViewById(R.id.layout_show);
        layout_show.setOnClickListener(this);
        tv_confirm=(TextView) findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(this);
    }

    /**
     * Description 按返回键退出
     *
     * @param keyCode
     * @param event
     * @return
     * @see android.app.Activity#onKeyDown(int, KeyEvent)
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            iphoneDialogBuilder idb = new iphoneDialogBuilder(HomeActivity.this);
            idb.setTitle("退出");
            idb.setMessage("您确定退出吗？");
            idb.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Tools.setSharedPreferencesboolen(Constant.isUpdate, false,context);

                    List<Activity> activities=myApplication.activities;
                    if(activities!=null && activities.size()>0)
                    {
                        for(Activity activity:activities)
                            activity.finish();
                    }
                    finish();
                }
            });
            idb.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {

                }
            });
            idb.show();

        }
        return true;
    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        switch (view.getId()) {
            // 首页
            case R.id.rb_first:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                }
                switchContent(homeFragment, Constant.homeFragmentTag);
                break;
            case R.id.rb_bankuai:
                if(banKuaiFragment==null)
                {
                    banKuaiFragment=new ModuleFragment();
                }
                switchContent(banKuaiFragment,Constant.banKuaiFragmentTag);
                break;
            // 资讯
            case R.id.rb_info:
                if (infoFragment == null)
                    infoFragment = new ConvenienceFragment();
                switchContent(infoFragment, Constant.infoFragmentTag);
                break;
            // 我的
            case R.id.rb_my:
                boolean isLogin=Tools.getSharedPreferencesboolen(Constant.isLoginIn,false,context);
                if(isLogin)
                {
                    if (mineFragment == null)
                        mineFragment = new MineFragment();
                    switchContent(mineFragment, Constant.mineFragmentTag);
                }else
                {
                    Intent intent = new Intent(context, Login_RegisterActivity.class);
                    myApplication.setSourceIntoLoginRegisterActivity(HomeActivity.class.getSimpleName());
                    startActivity(intent);
                    if (homeFragment == null) {
                        homeFragment = new HomeFragment();
                    }
                    switchContent(homeFragment, Constant.homeFragmentTag);
                }
                break;

            //遮罩层
            case R.id.layout_show:
                break;
            //确认按钮
            case R.id.tv_confirm:
                Tools.setSharedPreferencesboolen(Constant.SharePreferenceFirstLongClick,false,context);
                layout_show.setVisibility(View.GONE);
                break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(fragmentFlag.equals(HomeFragment.class.getSimpleName()))
        {
            rb_first.setChecked(true);
            rb_info.setChecked(false);
            rb_my.setChecked(false);
            rb_bankuai.setChecked(false);
        }else if(fragmentFlag.equals(InfoFragment.class.getSimpleName()))
        {
            rb_first.setChecked(false);
            rb_info.setChecked(true);
            rb_my.setChecked(false);
            rb_bankuai.setChecked(false);
        }else if(fragmentFlag.equals(BanKuaiFragment.class.getSimpleName()))
        {
            rb_first.setChecked(false);
            rb_info.setChecked(false);
            rb_my.setChecked(false);
            rb_bankuai.setChecked(true);
        }
        else if(fragmentFlag.equals(MineFragment.class.getSimpleName()))
        {
            rb_first.setChecked(false);
            rb_info.setChecked(false);
            rb_my.setChecked(true);
            rb_bankuai.setChecked(false);
            if(!Tools.getSharedPreferencesboolen(Constant.isLoginIn,false,context))
            {
                rb_first.setChecked(true);
                rb_info.setChecked(false);
                rb_my.setChecked(false);
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                }
                switchContent(homeFragment, Constant.homeFragmentTag);
            }
        }

    }
/*    @Override
    protected void onPause() {
        super.onPause();
        // 移除悬浮窗并停止悬浮窗服务（没有启用悬浮窗的话请忽视）
        stopService(new Intent(getApplicationContext(), FloatWindowService.class));
        MyWindowManager.removeSmallWindow(this);
    }*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除悬浮窗并停止悬浮窗服务（没有启用悬浮窗的话请忽视）
        stopService(new Intent(getApplicationContext(), FloatWindowService.class));
        MyWindowManager.removeSmallWindow(this);
    }

    private void switchContent(Fragment to, String tag) {
        if (mContent != to) {
            fragmentFlag=to.getClass().getSimpleName();
            FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(mContent).add(R.id.fragment_content, to, tag).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(mContent).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
            mContent = to;
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        // super.onSaveInstanceState(outState);
    }

    @Override
    public void clickIntoFragment() {
	layout_show.setVisibility(View.VISIBLE);
        rb_first.setChecked(false);
        rb_info.setChecked(true);
        rb_my.setChecked(false);
        rb_bankuai.setChecked(false);
        if (infoFragment == null)
            infoFragment = new ConvenienceFragment();
        switchContent(infoFragment, Constant.infoFragmentTag);
    }

    @Override
    public void onLoadContributorStart(String flag) {

    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            //banner
            if (flag.equals(VERSION_FLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    final String jsonMessage = JsonTools.objectToJsonString(object);
                    AbPermissionUtils.requestPermissionsResult(this, 1
                            , new String[]{
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,}
                            , new AbPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    //启动定位
                                    UpdateInfo updateInfo = JsonTools.jsonStringToObject(jsonMessage, UpdateInfo.class);
                                    if(updateInfo!=null && updateInfo.getVersionCode()!=null)
                                    {
                                        UpdateManager updateManager = new UpdateManager(context, updateInfo, myApplication.getVersion());
                                        updateManager.checkUpdate();
                                    }
                                }

                                @Override
                                public void onPermissionDenied() {

                                }
                            });

                }

            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {
    }

    @Override
    public void onLoadContributorError(String error, String flag) {

    }
}